package com.vueblog.webapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vueblog.webapi.entity.BlogEntity;
import com.vueblog.webapi.entity.TypeEntity;
import com.vueblog.webapi.enums.ResponseEnum;
import com.vueblog.webapi.exception.BusinessException;
import com.vueblog.webapi.mapper.BlogMapper;
import com.vueblog.webapi.mapper.TypeMapper;
import com.vueblog.webapi.request.BasePageRequest;
import com.vueblog.webapi.request.CreateOrUpdateTypeRequest;
import com.vueblog.webapi.response.BasePageResponse;
import com.vueblog.webapi.response.BaseResponse;
import com.vueblog.webapi.response.TypeBlogCountResponse;
import com.vueblog.webapi.service.ITypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author luosj
 * @since 2021-05-15
 */
@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper, TypeEntity> implements ITypeService {

    @Autowired
    private TypeMapper typeMapper;

    @Autowired
    private BlogMapper blogMapper;

    /**
     * 获取分类列表(分页模式)
     */
    @Override
    public BasePageResponse getTypePageList(BasePageRequest request) {
        Page<HashMap<String, Object>> page = new Page<>(request.getPageNum(), request.getPageSize());
        List<HashMap<String, Object>> pageList = typeMapper.getTypePageList(page);
        page.setRecords(pageList);
        return new BasePageResponse<>(ResponseEnum.SUCCESS, (int) page.getTotal(), page.getRecords());
    }

    /**
     * 获取分类列表(下拉列表模式)
     */
    @Override
    public BaseResponse getTypeList() {
        List<HashMap<String, Object>> list = typeMapper.getTypeList();
        return new BaseResponse(ResponseEnum.SUCCESS,list);
    }

    /**
     * 创建分类
     * @param request
     * @return
     */
    @Override
    @Transactional
    public BaseResponse createType(CreateOrUpdateTypeRequest request) {
        // 判断分类是否存在
        beforeCreate(request);
        // 创建分类实体类
        TypeEntity entity = new TypeEntity();
        // 注入name值
        entity.setName(request.getName());
        if (typeMapper.insert(entity) > 0) { // 判断分类是否添加成功
            // 返回成功信息
            return new BaseResponse(ResponseEnum.SUCCESS);
        }else {
            // 返回失败信息
            return new BaseResponse(ResponseEnum.DATABASE_ERROR);
        }

    }

    // 判断分类是否存在
    private void beforeCreate(CreateOrUpdateTypeRequest request) {
        Integer count = typeMapper.selectCount(new QueryWrapper<TypeEntity>().lambda()
                .eq(TypeEntity::getName, request.getName()));
        if (count > 0) {
            throw new BusinessException("该分类已存在");
        }
    }

    /**
     * 编辑分类
     */
    @Override
    @Transactional
    public BaseResponse updateTypeInfo(CreateOrUpdateTypeRequest request, String id) {
        // 判断分类是否存在并设置对象基本信息
        TypeEntity entity = beforeUpdate(request, id);
        if (typeMapper.updateById(entity) > 0) {// 判断分类是否修改成功
            // 返回成功信息
            return new BaseResponse(ResponseEnum.SUCCESS);
        }else {
            // 返回失败信息
            return new BaseResponse(ResponseEnum.DATABASE_ERROR);
        }
    }

    private TypeEntity beforeUpdate(CreateOrUpdateTypeRequest request, String id) {
        TypeEntity entity = typeMapper.selectById(id);
        if ( entity == null){
            throw new BusinessException("该分类不存在");
        }
        int count = this.count(new QueryWrapper<TypeEntity>().lambda()
                .eq(TypeEntity::getName, request.getName())
                .ne(TypeEntity::getId, id));
        if (count > 0) {
            throw new BusinessException("该分类已存在");
        }else {
            entity.setName(request.getName());
        }
        return entity;
    }

    /**
     * 删除分类
     */
    @Override
    @Transactional
    public BaseResponse deleteTypeInfo(String id) {
        // 删除分类
        int result = typeMapper.deleteById(id);
        if (result > 0) { // 判断分类是否删除
            // 创建修改条件器，将博客表中的typeId字段值设为null
            UpdateWrapper<BlogEntity> blogEntityUpdateWrapper = new UpdateWrapper<>();
            blogEntityUpdateWrapper.
                    eq("typeId", id)
                    .set("typeId", null);
            // 修改博客
            blogMapper.update(null, blogEntityUpdateWrapper);
            // 返回成功信息
            return new BaseResponse(ResponseEnum.SUCCESS);
        }
        // 返回失败信息
        return new BaseResponse(ResponseEnum.ERROR);
    }

    /**
     * 获取分类对应博客数量列表
     */
    @Override
    public BaseResponse getTypeBlogCountList() {
        List<HashMap<String, Object>> typeList = typeMapper.getTypeList();
        List<TypeBlogCountResponse> typeBlogCountList = new ArrayList<>();
        if (typeList != null) {
            for (HashMap<String, Object> type : typeList) {
                Integer count = blogMapper.selectCount(new QueryWrapper<BlogEntity>().lambda()
                        .eq(BlogEntity::getTypeId, type.get("typeId"))
                        .eq(BlogEntity::getPublished, true));
                TypeBlogCountResponse typeBlogCountResponse = new TypeBlogCountResponse(
                        (Long) type.get("typeId"), (String) type.get("typeName"), count);
                typeBlogCountList.add(typeBlogCountResponse);
            }
        }
        // 根据count降序排序
        typeBlogCountList.sort((x, y) -> -Double.compare(x.getBlogCount(), y.getBlogCount()));
        return new BaseResponse(ResponseEnum.SUCCESS, typeBlogCountList);
    }
}
